package com.nine.shop.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件读取工具类
 *
 * @author chenyi
 * date create on 2019/4/21
 */
public class FileUtil {

    //文件上传本地路径
    private static final String LOCAL_PATH = "E:/shop/static/images/image/";
    //文件上传网络路径
    private static final String NET_PATH = "http://localhost:8080/image/";

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件网络目录
     */
    public static String uploadFile(MultipartFile file) {
        if (file == null) return "fail: file is Null";
        //文件打包目录
        //获取今日时间 (年-月-日)
        String date = DateFormatUtil.getOnlyDayTime();
        String packagePath = createPackageFolder(date);
        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;
        String[] suffixArray = originalFileName.split("\\.");
        String suffix = suffixArray[suffixArray.length - 1];
        String fileName = DateFormatUtil.getFullDayTime() + "." + suffix;
        try {
            // 存储文件
            file.transferTo(new File(packagePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return NET_PATH + date + "/" + fileName;
    }

    /**
     * 创建时间分类的文件夹
     *
     * @return 打包目录-本地路径
     */
    private static String createPackageFolder(String date) {
        //创建时间命名文件夹
        String packagePath = LOCAL_PATH + "/" + date;
        File filePath = new File(packagePath);
        if (!filePath.exists()) {
            //创建目标文件夹
            if (!filePath.mkdir()) {
                return "fail: filePath is Null";
            }
        }
        return LOCAL_PATH + date + "/";
    }
}
